import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, 
  ScrollView,ImageBackground,StatusBar,
  TouchableOpacity,Modal
} from 'react-native';
import Video from 'react-native-video';
import MusicScan from '../../component/MusicScan'
import { TipModal } from '../../component/Tips';
import Toast, {DURATION} from 'react-native-easy-toast'
import BackButton from '../../component/BackButton';
import MyButton from '../../component/MyButton';
import ShareView from '../../component/ShareView';
import DeviceStorage from '../../common/DeviceStorage';
//import VideoPlayerComp from '../../component/VideoPlayerComp';
import {jumpPage,width} from '../../common/common';
import {BASEURL} from '../../api/api'
var IMG_URL =  BASEURL+'image/showImage?imageName=';
export default class TempDetail extends Component{
  static navigationOptions = ({ navigation }) =>{
    return{
      title:navigation.getParam('tempTitle'),
      headerRight:(<View></View>),
      headerLeft:<BackButton navigation = {navigation}/>
    }
  };
  constructor(props){
    super(props);
    this.state = ({
      detail: {

      },
      userId:this.props.navigation.getParam('userId'),
      modal: false,
      tempId: this.props.navigation.getParam('tempId'),
			edit: this.props.navigation.getParam('edit'),
			isColl:false,
			collectId:[]
    })
    //console.log('navig',this.props.navigation)
  }
  componentWillMount(){
    DeviceStorage.get('user').then((user)=>{
      if(user){
        let userInfo = JSON.parse(user);
        this.setState({
          userId: userInfo.userId
        },()=>{
          this._getDetailInfo();
          this._judgeIsColl();
        })
      } else {
        this._getDetailInfo();
      }
		})
		//收藏
		// DeviceStorage.get('collect').then((collect)=>{
		// 	let collectId;
    //   if(collect){
    //     collectId = JSON.parse(collect);
    //   } else {
    //     collectId = [];
		// 	}
		// 	this.setState({
		// 		collectId: collectId
		// 	})
		// 	this.setState({
		// 		isColl: collectId.includes(this.props.navigation.getParam('tempId'))
		// 	})
    // })
	}
	_collect(){
		let {collectId, tempId} = this.state;
		let oldTempId = this.props.navigation.getParam('tempId');
		if(this.state.isColl){
			//this.refs.toast.show("取消收藏");
      this._collToServer(2);
			//collectId.splice(collectId.indexOf(oldTempId),1);
		} else {
      this._collToServer(1);
			//collectId.push(this.props.navigation.getParam('tempId'));
			//this.refs.toast.show("收藏成功");
		}
		//DeviceStorage.save('collect',JSON.stringify(collectId));
		// this.setState({
		// 	isColl:!this.state.isColl
		// })
  }
  _collToServer(type){
    let url = 'per/userColl?tempId=';
    if(type == 2){
      url = 'per/userCancelColl?tempId=';
    }
    fetch(BASEURL+url
      +this.props.navigation.getParam('tempId')+'&userId='+this.state.userId)
    .then(res=>res.json())
    .then(response=>{
      //console.log(response);
      this.refs.tipModal._close();
      if(response.succ == '1'){
        if(type == 1){
          this.refs.toast.show("收藏成功");
        } else {
          this.refs.toast.show("取消收藏");
        }
        this.setState({
          isColl: !this.state.isColl
        })
      } else {
        this.refs.toast.show("获取失败");
      }
      
    })
    .catch(err=>{
      this.refs.tipModal._close();
      this.refs.tipModal._error('获取失败',1500);
    })
  }
  _judgeIsColl(){
    fetch(BASEURL+'per/isColl?tempId='+this.props.navigation.getParam('tempId')+'&userId='+this.state.userId)
    .then(res=>res.json())
    .then(response=>{
      //console.log(response);
      this.refs.tipModal._close();
      if(response.succ == '1'){
        this.setState({
          isColl: response.isColl
        })
      } 
      
    })
    .catch(err=>{
      this.refs.tipModal._close();
      console.log(err);
    })
  }
  _getDetailInfo(){
    this.refs.tipModal._loading();
    fetch(BASEURL+'temp/detail?tempId='+this.state.tempId+'&userId='+this.state.userId)
    .then(res=>res.json())
    .then(response=>{
      //console.log(response);
      this.refs.tipModal._close();
      if(response.succ == '1'){
				response.temp.img = {uri: IMG_URL+response.temp.tempImg}
        this.setState({
          detail: response.temp,
          tempId: response.temp.tempId
        })
      } else {
        this.refs.toast.show("获取失败");
      }
      
    })
    .catch(err=>{
      this.refs.tipModal._close();
      this.refs.tipModal._error('获取失败',1500);
    })
  }
  _player(){
    // MusicScan.openPicker({
    //   width: 300,
    //   height: 400,
    //   cropping: false
    // });
		//MusicScan.show("Awesome", MusicScan.SHORT);
		let {detail} = this.state;
		if(detail.mp4){
			jumpPage(this.props.navigation, 'playerVideo',{videoUrl:detail.mp4});
		} else {
			this.refs.toast.show("暂无视频");
		}
    
    
  }
  _goEdit(){
    //alert(this.state.userId);
    DeviceStorage.get('user').then((user)=>{
      console.log('user=',user)
      if(user){

        let userInfo = JSON.parse(user);
        console.log('1',userInfo.userId)
        if(!userInfo.userId){
          
        } else {
          jumpPage(this.props.navigation,'tempEdit',{
						tempImg: this.state.detail.tempImg,
						tempId: this.state.tempId, 
            mp3: this.state.detail.mp3,
            userId: this.state.userId, 
            tempTitle: this.props.navigation.getParam('tempTitle')
          });
        }
      } else {
        this.refs.toast.show("请登录",1500);
          setTimeout(()=>{
            this.props.navigation.navigate('login',{
              edit:'1',
              tempId: this.state.tempId,
              tempTitle: this.props.navigation.getParam('tempTitle')
            });
            //jumpPage(this.props.navigation,'login');
          },1500);
      }
    })
    /**
    if(!this.state.userId && !this.state.edit){
      this.refs.toast.show("请登录",1500);
      setTimeout(()=>{
        this.props.navigation.navigate('login',{
          edit:'1',
          tempId: this.state.tempId,
          tempTitle: this.props.navigation.getParam('tempTitle')
        });
        //jumpPage(this.props.navigation,'login');
      },1500);
    } else {
      //this.refs.toast.show("已登录");
      jumpPage(this.props.navigation,'tempEdit',{tempId: this.state.tempId, 
      mp3: this.state.detail.mp3,
      userId: this.state.userId, 
      tempTitle: this.props.navigation.getParam('tempTitle')});
    }
    */
  }
  render(){
    //require('../../images/temp/group0.png')
    let img = this.state.detail.tempImg;
    // /alert(img);
    if(img && img.indexOf('http') == -1){
      img = IMG_URL + img;
    }
    return(
      <View style={styles.container}>
				<StatusBar hidden={false}/>
        <ImageBackground style={styles.mainImg} source={{uri:img}}>
          <TouchableOpacity style={styles.playView} onPress={()=>{this._player()}}>
            <Image style={styles.palyIcon} source={require('../../images/temp/icon_play.png')}/>
          </TouchableOpacity>
        </ImageBackground>
        <Text style={styles.contentText}>{this.state.detail.tempDesc}</Text>
        <View style={{flex:1,marginTop:10,borderWidth:0,borderColor:'red',backgroundColor:'#f0f0ff'}}>
          <ShareView item={this.state.detail} hasClose={false} toast={this.refs.toast}/>
          <View style={{flex:1}}></View>
          {/* <View>
            <Image style={{width:width,height:width*0.2}} source={require('../../images/temp/icon_ad.png')}/>
					</View> */}
					<TouchableOpacity onPress={()=>this._collect()}
						style={{flexDirection:'row',
						justifyContent:'flex-end',alignItems:'center',
						paddingRight:10,paddingBottom:10,marginBottom:10,marginRight:10}}>
						<Image style={styles.collImg} 
							source={this.state.isColl?require('../../images/icon_coll_sel.png')
								:require('../../images/icon_coll_nor.png')}/>
						<Text>{this.state.isColl?'已收藏':'收藏  '}</Text>
					</TouchableOpacity>
        </View>
        <MyButton btnStyle={{marginTop:0,marginLeft:20,marginRight:20,marginBottom:10,height:40}} text='使用' press={()=>this._goEdit()}/>
        {/* <VideoPlayerComp modal={this.state.modal} close={()=>{this.setState({modal: false})}} refs=""/> */}
        <Toast ref="toast" position='bottom' positionValue={200} />
        <TipModal ref="tipModal"/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
	collImg:{
		marginRight:5,
		width:18,
		height:18
	},
  row:{
    flexDirection:'row',
    alignItems:'center',
    borderBottomWidth:1,
    borderBottomColor:'#ccc',
    paddingTop:10,
    paddingBottom:10,
  },
  contentText:{
    marginLeft:10,
    fontSize:16,
    color:'#333',
  },
  playView:{
    backgroundColor:'rgba(0,0,0,0.4)',
    borderRadius:20,
    width:40,
    height:40,
    justifyContent:'center',
    alignItems:'center',
  },
  palyIcon:{
    left:1,
    width:30,
    height:30,
  },
  mainImg:{
    margin:10,
    width:width-20,
    height:(width-20)*0.6,
    justifyContent:'center',
    alignItems:'center',
  },
  container: {
    backgroundColor:'#fff',
    flex: 1,
  },
})